package com.longrise.android.byjk.plugins.aboutme.personalInfo.change;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.utils.PhoneUtils;
import com.longrise.android.byjk.widget.view.InputBoxView;
import com.longrise.common.datasource.remote.LoadDataManager;


/**
 * 修改手机号
 * Created by sujizhong on 2017/2/10.
 */

public class ChangePhoneActivity extends BaseActivity implements View.OnClickListener, TextWatcher {

    private Toolbar mTitle;

    private TextView mTvHint;
    private TextView mTvBotHint;
    private EditText mEtPhone;
    private TextView mTvGetCode;
    private TextView mTvPhone;
    private EditText mEtConfirmCode;
    private Button mBtnConfrim;

    private View mLoading;

    private boolean mIsChange;
    private boolean mIsRunLogin;
    private ImageView mForgetPwd;

    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        if (savedInstanceState != null) {

        }
        return R.layout.activity_changephone;
    }


    @Override
    public void initView() {
        mTvHint = (TextView) findViewById(R.id.tv_cp_sign);
        mTvBotHint = (TextView) findViewById(R.id.tv_bottom_hint);
        mEtPhone = (EditText) findViewById(R.id.forgetpasword_text);
        mEtPhone.setHint(getString(R.string.personal_phone_no));
        mTvGetCode = (TextView) findViewById(R.id.forgetpasword_pic2);
        mTvPhone= (TextView) findViewById(R.id.tv_cp_phone);
        InputBoxView ibView = (InputBoxView) findViewById(R.id.iv_cp_confrimcode);
        mEtConfirmCode = ibView.getEditText();
        mBtnConfrim = (Button) findViewById(R.id.btn_cp_confrim);
        mBtnConfrim.setEnabled(false);
        mForgetPwd = (ImageView)findViewById(R.id.forgetpasword_pic1);
        mLoading = findViewById(R.id.rela_load_xqpc);
        mLoading.setVisibility(View.GONE);

        mEtPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String phone = mEtPhone.getText().toString().trim();
                if(TextUtils.isEmpty(phone)||"".equals(phone)){
                    mForgetPwd.setSelected(false);
                }else{
                    mForgetPwd.setSelected(true);
                }

            }
        });

        setData();
        onEvent();
        initTitle();

    }

    private void setData() {
        String moblie = UserInfor.getInstance().getIsopenmobilelogin();
        mIsRunLogin = moblie != null && moblie.equals("1");
        String userphone = UserInfor.getInstance().getUserphone();

        //xkj 20170420 更改已开通后的显示
        String tips = "";
        String usersfzh = UserInfor.getInstance().getUsersfzh();
        String userName = UserInfor.getInstance().getUserName();
        if (TextUtils.isEmpty(usersfzh)) {//身份证号码为空
            tips = "当前账号：" + userName;
        } else {
            tips = "当前账号：" + usersfzh;
        }
        String tips2 =userphone;
        if (mIsRunLogin) { //已开通快捷登录
            mTvPhone.setText(Html.fromHtml("<font color='#4D4D4D'>" + tips2 + "</font>"));
            mTvBotHint.setText(getString(R.string.mobile_is_getpw));
        } else {
            mTvPhone.setText(userphone);
            mTvBotHint.setText(getString(R.string.mobile_is_getpw));
        }

        // mTvHint.setText(mIsRunLogin ? getString(R.string.isrunlogin) + userphone : getString(R.string.cp_phone) + userphone);

        // mTvBotHint.setText(mIsRunLogin ? getString(R.string.mobile_is_getpw_login) : getString(R.string.mobile_is_getpw));
    }

    private void initTitle() {
        mTitle = (Toolbar) findViewById(R.id.byjk_toolbar);
        mTitle.setTitle(getString(R.string.xgphone));
        setSupportActionBar(mTitle);
        mTitle.setNavigationOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                close();
            }
        });
    }

    private void onEvent() {
        if (mTvGetCode != null) {
            mTvGetCode.setOnClickListener(this);
        }
        if (mBtnConfrim != null) {
            mBtnConfrim.setOnClickListener(this);
//            mBtnConfrim.setClickable(false);
        }
        mTvGetCode.addTextChangedListener(this);
        mEtConfirmCode.addTextChangedListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.forgetpasword_pic2:
                getConfirmCode();
                break;

            case R.id.btn_cp_confrim:
                request();
                break;
        }
    }

    /**
     * 修改手机号
     */
    private void request() {
        String phone = mEtPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            showToast(getString(R.string.phonenum_isnull));
            return;
        }
        if (!PhoneUtils.isPhoneNumber(phone)) {
            showToast(getString(R.string.phone_type_error));
            return;
        }
        String singleCode = mEtConfirmCode.getText().toString().trim();
        if (TextUtils.isEmpty(singleCode)) {
            showToast(getString(R.string.singlecode_isnull));
            return;
        }
        EntityBean changeBean = new EntityBean();
        changeBean.set("userid", UserInfor.getInstance().getUserid());
        changeBean.set("cardno", UserInfor.getInstance().getUsersfzh());
        changeBean.set("mobile", phone);
        changeBean.set("mobilecode", singleCode);
        final EntityBean reqBean = new EntityBean();
        reqBean.set("bean", changeBean);

        showLoading(true);
        setBtnStatus(false);

        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl, "bbt_user_uPersonMobile", reqBean, new LoadDataManager.OnRequestCallListener() {

            @Override
            public void onSuccess(String key, String service, Object result) {
                try {
                    EntityBean resultBean = (EntityBean) result;
                    int resultstate = resultBean.getInt("resultstate");
                    if (resultstate == 1) {
                        EntityBean bean = resultBean.getBean("result");
                        UserInfor.getInstance().setUserphone(bean.getString("mobile"));
                        mIsChange = true;
                        close();
                    } else {
                        showToast(resultBean.getString("resultdesc"));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished(String key, String service) {
                showLoading(false);
                setBtnStatus(true);
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                showToast(getString(R.string.nonetwork));
            }
        });
    }

    /**
     * 获取验证码
     */
    private void getConfirmCode() {
        String phone = mEtPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            showToast(getString(R.string.phonenum_isnull));
            return;
        }
        if (!PhoneUtils.isPhoneNumber(phone)) {
            showToast(getString(R.string.txsjh));
            return;
        }
        if (phone.equals(UserInfor.getInstance().getUserphone())) {
            showToast(getString(R.string.phone_bundle_xt));
            return;
        }
        EntityBean bean = new EntityBean();
        bean.set("usersfzh", UserInfor.getInstance().getUsersfzh());
        bean.set("bindphone", phone);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);

        setWeightStatus(false, getString(R.string.getmoblieconfrimcode), "#666666");
        showLoading(true);

        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl, "bbt_login_getBindPhoneCode", fbean, new LoadDataManager.OnRequestCallListener() {

            @Override
            public void onSuccess(String key, String service, Object result) {
                try {
                    EntityBean bean = (EntityBean) result;
                    int resultstate = (Integer) bean.get("resultstate");
                    String resultdesc = (String) bean.get("resultdesc");
                    if (resultstate == 1) {
                        timer.start();
                    } else {
                        getVftoNorm(); //可能账号与手机号码不匹配 用户需重新输入后倒计时
                    }
                    showToast(resultdesc);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished(String key, String service) {
                showLoading(false);
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                getVftoNorm();
                showToast(getString(R.string.nonetwork));
            }
        });
    }

    private CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            mTvGetCode.setText("重新获取(" + millisUntilFinished / 1000 + "s)");
        }

        @Override
        public void onFinish() {
            getVftoNorm();
        }
    };

    /**
     * 恢复获取验证码按钮状态
     */
    private void getVftoNorm() {
        setWeightStatus(true, getString(R.string.getmoblieconfrimcode), "#0791FF");
    }

    private void setWeightStatus(boolean isClickable, String text, String textColor) {
        mTvGetCode.setClickable(isClickable);
        mTvGetCode.setText(text);
        mTvGetCode.setTextColor(Color.parseColor(textColor));
    }

    /**
     * 设置修改手机号btn状态
     */
    private void setBtnStatus(boolean isClick) {
        mBtnConfrim.setClickable(isClick);
    }

    private void close() {
        setResult(100, new Intent().putExtra("key", mIsChange));
        finish();
    }

    private void showLoading(boolean isLoading) {
        mLoading.setVisibility(isLoading ? View.VISIBLE : View.GONE);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            close();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 检查是否全部填写
     *
     * @return 全部有填写 返回true
     */
    private boolean checkText() {
        //手机号
        String phoneNum = mEtPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNum)) {
            return false;
        }
        //短信验证码
        String mIbvVfcodeText = mEtConfirmCode.getText().toString().trim();
        if (TextUtils.isEmpty(mIbvVfcodeText)) {
            return false;
        }
        return true;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        boolean b = checkText();
        if (b) {
            mBtnConfrim.setEnabled(true);
        } else {
            mBtnConfrim.setEnabled(false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
